package client.ui;

import java.io.*;
import java.net.URL;
import java.util.*;

import com.sun.javafx.robot.impl.FXRobotHelper;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.awt.*;


public class historyUIController implements Initializable {


    String path = new textUIControlller().path;

    @FXML
    private TextField search;//查找消息记录
    @FXML
    private Button derive;//导出消息记录
    @FXML
    private TextArea display;//显示消息记录
    @FXML
    private Label savedTips;//消息记录导出成功后的提示
    @FXML
    private Label ensureSaved;//确认
    private String messages = null;//将消息记录暂时存为字符串

    private String result = " ";//搜索后的结果

    //创建要操作的文件路径和名称


    // @Override
    public void initialize(URL location, ResourceBundle resources) {
        DisplayMessage();

        //查找栏内容变化时  进行查找

        search.textProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {


                String keyMessage = search.getText();
                if (keyMessage.length() != 0 && keyMessage != null) {
                    SearchKeyword(new File(path), keyMessage);

                    display.setText(result);
                    result = " ";
                } else {

                    display.setVisible(true);
                    display.setText(messages);
                }

            }
        });

    }


    public void onDeriveClicked(MouseEvent mouseEvent) {
        //从本地读取消息记录
        //导出
        derive.setOnAction(event -> {
            //得到用户导出的文件路径
            FileChooser fileChooser = new FileChooser();
            FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("txt files (*.txt)", "*.txt");
            fileChooser.getExtensionFilters().add(extFilter);
            Stage s = new Stage();

            File file = fileChooser.showSaveDialog(s);
            if (file == null)
                return;
            if (file.exists()) {//文件已存在，则删除覆盖文件
                file.delete();
            }
            String exportFilePath = file.getAbsolutePath();

            FileReader r = null;
            //由于IO操作会抛出异常，因此在try语句块的外部定义FileWriter的引用
            FileWriter w = null;
            try {
                r = new FileReader(path);

                while (true) {
                    int temp = r.read();
                    if (temp == -1) {
                        break;
                    }
                    w = new FileWriter(exportFilePath, true);

                    //将字符串写入到流中，\r\n表示换行想有好的
                    w.write(String.valueOf((char) temp));
                    System.out.print(String.valueOf((char) temp));
                    //如果想马上看到写入效果，则需要调用w.flush()方法
                    w.flush();

                    savedTips.setText("已成功保存在:" + exportFilePath);
                    savedTips.setStyle("-fx-text-alignment: center;" +
                            "-fx-text-fill: darkgoldenrod;" +
                            "-fx-background-color: gold");
                    savedTips.setVisible(true);
                    ensureSaved.setText("确认");
                    ensureSaved.setStyle("-fx-text-fill: blue");
                    ensureSaved.setVisible(true);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (r != null) {
                    try {
                        r.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

        });
    }

    public void SearchKeyword(File file, String keyword) {
        //参数校验
       // verifyParam(file, keyword);

        //行读取
        LineNumberReader lineReader = null;
        try {
            lineReader = new LineNumberReader(new FileReader(file));
            String readLine = null;
            int count = 0;
            while ((readLine = lineReader.readLine()) != null) {
                //判断每一行中,出现关键词的次数
                int index = 0;
                int next = 0;
                int times = 0;//出现的次数


                //判断次数
                while ((index = readLine.indexOf(keyword, next)) != -1) {
                    next = index + keyword.length();
                    times++;
                }
                if (times > 0) {
                    //lineReader.setLineNumber(lineReader.getLineNumber()-1);

                    result += "第" + lineReader.getLineNumber() + "行" + "出现 \"" + keyword + "\""
                            + times + " 次" + '\n' + "\"   " + readLine + "  \"" + '\n';
                    count++;

                    //  System.out.println(readLine);
                    // System.out.println("第"+ lineReader.getLineNumber() +"行" + "出现 "+keyword+" 次数: "+times);

                }

            }
            result = ("       ------------------" + count + "  条相关内容---------------\n")+result;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            close(lineReader);
        }
    }

    /**
     * 参数校验
     
    private void verifyParam(File file, String keyword) {
        //对参数进行校验证
        if (file == null) {
            throw new NullPointerException("the file is null");
        }
        if (keyword == null || keyword.trim().equals("")) {
            throw new NullPointerException("the keyword is null or \"\" ");
        }

        if (!file.exists()) {
            throw new RuntimeException("the file is not exists");
        }
        //非目录
        if (file.isDirectory()) {
            throw new RuntimeException("the file is a directory,not a file");
        }

        //可读取
        if (!file.canRead()) {
            throw new RuntimeException("the file can't read");
        }
    }

    /**
     * 关闭流
     */
    private void close(Closeable able) {
        if (able != null) {
            try {
                able.close();
            } catch (IOException e) {
                e.printStackTrace();
                able = null;
            }
        }
    }

    //显示消息记录的函数
    public void DisplayMessage() {

        FileReader r = null;
        try {
            r = new FileReader(path);

            while (true) {
                int temp = r.read();
                if (temp == -1) {
                    break;
                }

                display.setVisible(true);
                display.appendText(String.valueOf((char) temp));
                messages = display.getText();

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (r != null) {
                try {
                    r.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //控制Label提示的显示的函数

    public void onEnsureSavedClicked(MouseEvent mouseEvent) {
        savedTips.setVisible(false);
        ensureSaved.setVisible(false);

    }
}

